package org.rcy.ruicingmarket.common.utils;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


public class ObjectUtils {
public static Map convertObjToMap(Class clazz, Object obj) throws IllegalAccessException {
	DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
	Map<String, String> map = new HashMap<String, String>();
	Field[] fields = clazz.getDeclaredFields();
	for (Field field : fields) {
		field.setAccessible(true);
		if(field.get(obj)==null)
		{
			map.put(field.getName(),"");
			continue;
		}
		if(field.getType().getSimpleName().equals("Integer"))
		{
			map.put(field.getName(), String.valueOf((Integer) field.get(obj)));
			continue;
		}
		if(field.getType().getSimpleName().equals("Date"))
		{
			map.put(field.getName(), dateFormat.format((Date) field.get(obj)));
			continue;
		}
		map.put(field.getName(), (String) field.get(obj));
	}
	return map;
}
	public static <T> T mapToBean(Map map, Class<T> beanClass) throws Exception {
		DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
	T object = beanClass.newInstance();
		Field[] fields = object.getClass().getDeclaredFields();
		for (Field field : fields) {
			int mod = field.getModifiers();
			if (Modifier.isStatic(mod) || Modifier.isFinal(mod)) {
				continue;
			}
			field.setAccessible(true);
			if (map.containsKey(field.getName())) {
				if(field.getType().getSimpleName().equals("Integer"))
				{
					field.set(object, map.get(Integer.parseInt((String) field.getName())));
					continue;
				}
				if(field.getType().getSimpleName().equals("Date"))
				{
					field.set(object, map.get(dateFormat.parse((String) field.getName())));
					continue;
				}
				field.set(object, map.get((String)field.getName()));
			}
		}
		return object;
	}

}